package com.cskaoyan.config;

import com.cskaoyan.realm.AdminRealm;
import com.cskaoyan.realm.WxRealm;
import com.cskaoyan.shiro.LoginToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author Fantasylkh
 */
public class LoginAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        Collection<Realm> originRealms = this.getRealms();
        LoginToken token = (LoginToken) authenticationToken;
        String type = token.getType();
        List<Realm> realmList = new ArrayList<>();
        for (Realm originRealm : originRealms) {
            if (originRealm.getName().toLowerCase().contains(type)) {
                realmList.add(originRealm);
            }
        }
        if (originRealms.size() == 1) {
            if (realmList.iterator().next() instanceof WxRealm) {
                return this.doSingleRealmAuthentication((WxRealm) realmList.iterator().next(), authenticationToken);
            }
            if (realmList.iterator().next() instanceof AdminRealm) {
                return this.doSingleRealmAuthentication((AdminRealm) realmList.iterator().next(), authenticationToken);
            }
            return this.doSingleRealmAuthentication(realmList.iterator().next(), authenticationToken);
        } else {
            return this.doMultiRealmAuthentication(realmList, authenticationToken);
        }
    }
}
